package com.ease.util {
   import flash.utils.ByteArray;

   import mx.utils.Base64Decoder;
   import mx.utils.Base64Encoder;

   /**
    * Basic utility to compress and uncompress the data.
    */
   public class CompressionUtil {
      /**
       * Called to compress the data object and encoding to base64 string.
       *
       * @param data The data object to compress and encode.
       * @return The base64 encoded string containing the compressed data.
       */
      public static function compressAndEncode(data:Object):String {
         return encode(compress(data));
      }

      /**
       * Called to decode the base64 string and uncompress to original object.
       *
       * @param str The base64 encoded string.
       * @return The original data from the compressed stream.
       */
      public static function decodeAndUncompress(str:String):Object {
         return uncompress(decode(str));
      }

      /**
       * Compress the given data object into byte stream for non-overhead
       * transport over the wire.
       *
       * @param data The data to compress.
       * @return The byte array of compressed data.
       */
      public static function compress(data:Object):ByteArray {
         var b:ByteArray = new ByteArray();
         b.writeObject(data);
         b.compress();
         return b;
      }

      /**
       * Given a ByteArray stream, this function will uncompress the stream
       * and retrieves the data
       *
       * @param b The byte array stream.
       * @return The original data object.
       */
      public static function uncompress(b:ByteArray):Object {
         b.uncompress();
         return b.readObject();
      }

      /**
       * Given a byte array, this function will encode the data to base64 string.
       *
       * @param b The input byte array to encode.
       * @return The base64 encoding string.
       */
      public static function encode(b:ByteArray):String {
         var encoder:Base64Encoder = new Base64Encoder();
         encoder.encodeBytes(b);
         return encoder.toString();
      }

      /**
       * Given a base64 encoded string, this function will decode to byte
       * array stream.
       *
       * @param str The base64 encoding string.
       * @param The byte array stream containing the decoded data.
       */
      public static function decode(str:String):ByteArray {
         var decoder:Base64Decoder = new Base64Decoder();
         decoder.decode(str);
         return decoder.toByteArray();
      }
   }

}